<?php

namespace plugin\admin\app\common\zthysms;

use plugin\admin\app\constant\v1\CommonConstant;
use plugin\admin\app\service\v1\OptionService;
use support\Log;

class Api
{

    /**
     * 模板短信发送
     *
     * @param string $mobile
     * @param string $code
     * @param string $event
     */
    public static function send($mobile, $code, $event)
    {
        date_default_timezone_set('PRC'); //设置时区

        $config = OptionService::getConfig('sms');
        if ($event == CommonConstant::SMS_0) {
            $tpId = $config['zthysms_template_code_1'];
            $tpContent = ['verify_code' => $code];
        }
        if ($event == CommonConstant::SMS_1) {
            $tpId = $config['zthysms_template_code_2'];
            $tpContent = ['valid_code' => $code];
        }

        //模板信息发送demo
        $url = "https://api-shss.zthysms.com/v2/sendSmsTp";
        $tKey = time();
        $password = md5(md5($config['zthysms_password']) . $tKey);
        $records = array();
        $record = array("mobile" => $mobile, "tpContent" => $tpContent);
        array_push($records, $record);

        $data = array(
            'username' => $config['zthysms_username'], //用户名
            'password' => $password, //密码
            'tKey' => $tKey, //tKey
            'signature' => '【'.$config['zthysms_sign_name'].'】',
            'tpId' => $tpId, //模板id
            'records' => $records
        );
        $result = self::httpPost($url, $data);
        return $result;
    }

    public static function httpPost($url, $data)
    {
        $msg = '【短信配置】 ';

        $log = Log::channel('zthysms');
        $log->info($msg . 'request ', $data);

        // 模拟提交数据函数
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
//        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_POST, true); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, false); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
        curl_setopt($curl, CURLOPT_HEADER, false); //开启header
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8'
        )); //类型为json
        // 执行请求并获取响应
        $response = curl_exec($curl);
        // 检查错误
        if (curl_errno($curl)) {
            return V(1, $msg.'请求错误: ' . curl_error($curl));
        }
        // 关闭cURL资源
        curl_close($curl);

        $result = json_decode($response, true);
        $log->info($msg . 'data ', $result);
        if($result['code'] != 200){
            return V(1, $msg.self::getErrorMessage($result['code']));
        }
        return V(0,$result['msg']);
    }

    /**
     * 获取详细错误信息
     *
     * @param string|int $code 错误码
     * @return string 错误描述信息
     */
    public static function getErrorMessage($code)
    {
        // 主错误码映射表
        $message = [
            // 成功
            '200' => '提交成功',

            // 业务错误码
            '4000' => '余额不足',
            '4001' => '用户名错误',
            '4002' => '密码不能为空',
            '4004' => '手机号码错误',
            '4006' => 'IP鉴权错误',
            '4007' => '用户禁用',
            '4008' => 'tKey错误',
            '4009' => '密码错误',
            '4013' => '定时时间错误',
            '4014' => '模板错误',
            '4015' => '扩展号错误',
            '4019' => '用户类型错误',
            '4023' => '签名错误',
            '4025' => '模板变量内容为空',
            '4026' => '手机号码数最大2000个',
            '4027' => '模板变量内容最大200组',
            '4029' => '请使用post请求',
            '4030' => 'Content-Type请使用application/json',
            '4031' => '模板名称不能为空',
            '4032' => '模板类型必须是1,2,3的数字',
            '4033' => '模板格式必须是1,2的数字',
            '4034' => '模板内容不能为空',
            '4035' => '模板名称已存在',
            '4036' => '添加模板信息失败',
            '4037' => '模板名称最大20字符',
            '4038' => '模板内容最大450字符',
            '4039' => '模板内容不能有【】',
            '4040' => '模板内容缺少变量值或规则错误',
            '4041' => '模板内容中变量规范错误',
            '4042' => '模板内容中变量个数最大16个',
            '4043' => '检测系统敏感词错误',
            '4044' => '接口24小时限制提交次数超限',
            '4045' => '查询模板状态失败',
            '4046' => '查询模板状态1秒1次',
            '4047' => '模板不存在',
            '4048' => '信息消息id为空',
            '4049' => '每批取消定时信息最大100组',
            '4050' => '取消定时信息失败',
            '4051' => '签名为空',
            '4052' => '签名长度最大20',
            '4053' => '签名格式错误',
            '4054' => '签名不存在',
            '4055' => '消息不存在',
            '4056' => '消息id或手机号为空',
            '4057' => '手机号为空',
            '4058' => '手机号最大50个',
            '4059' => '取消失败',
            '4060' => '时间错误',
            '4061' => '最大查询30天',
            '4062' => '账号未认证',
            '4063' => '模板Id不正确',
            '4064' => '链接不正确',
            '4067' => '未开启回执报告',
            '4068' => '短链服务未开通，请联系商务',
            '4072' => 'api能力未开通，请联系商务',
            '9998' => 'JSON解析错误',
            '9999' => '非法请求',

            // CMPP连接错误代码
            '0' => '成功',
            '1' => '消息结构错',
            '2' => '非法原地址',
            '3' => '认证错',
            '4' => '版本错误',
            '56' => '连接数超限',
            '57' => 'IP错误',

            // CMPP提交错误代码
            '10' => '手机号码为空', // 注意：这里0已经被定义为成功，所以从10开始
            '11' => '命令字错',
            '12' => '消息序号重复',
            '13' => '消息长度错',
            '14' => '资费代码错',
            '15' => '超过最大信息长',
            '16' => '业务代码错',
            '17' => '流量控制错',
            '18' => '内容编码格式错',
            '19' => '手机号码为空',
            '20' => '接入号错',
            '99' => '其他错误',
        ];

        // 将code转换为字符串进行查找
        $codeStr = (string)$code;
        if (isset($message[$codeStr])) {
            return $message[$codeStr];
        }
        // 如果没找到，返回原始错误码
        return "未知错误码: {$codeStr}";
    }
}